package org.domeos.framework.api.task;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.domeos.framework.api.biz.alarm.AlarmBiz;
import org.domeos.framework.api.biz.monitor.MonitorBiz;
import org.domeos.framework.api.model.alarm.UserGroupBasic;
import org.domeos.framework.api.model.alarm.UserInfo;
import org.domeos.framework.api.model.monitor.ComponentStatus;
import org.domeos.framework.api.service.alarm.AlarmSenderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 
 * @author lixiaokai
 *
 */

@Component
public class ComponentMonitor {
	@Autowired
	MonitorBiz monitorBiz;
	
	@Autowired
    AlarmSenderService alarmSenderService;
	
	@Autowired
    AlarmBiz alarmBiz;
	
	private static AtomicBoolean started = new AtomicBoolean(false);

	private static Logger logger = LoggerFactory
			.getLogger(ProductLineUpdater.class);

	private ScheduledExecutorService scheduledExecutor = Executors
			.newScheduledThreadPool(1);
	
	@PostConstruct
	public void init() {
		if (started.compareAndSet(false, true)) {
			logger.info("init {}, start scheduled task checker.",
					ComponentMonitor.class.toString());
			scheduledExecutor.scheduleWithFixedDelay(
					new ComponentChecker(), 1, 5, TimeUnit.MINUTES);
		}
	}
	
	private class ComponentChecker implements Runnable {
		private List<ComponentStatus> lastComponentStatus = monitorBiz.getComponent();
		@Override
		public void run() {
			List<ComponentStatus> currentComponentStatus = monitorBiz.getComponent();
			for(ComponentStatus component: currentComponentStatus) {
				if("False".equals(component.getStatus())) {
					// send mail
					String subject = "[异常] 组件报警  " + component.getComponent();
					String content = "状态： " + component.getStatus() + "\r\n" + "组件： " + component.getComponent() + "\r\n" + "主机: " + component.getHostname();
					sendMail(subject, content);
				}else {
					if(!include(lastComponentStatus, component)) {
						//send mail for recovery
						String subject = "[恢复] 组件报警  " + component.getComponent();
						String content = "状态： " + component.getStatus() + "\r\n" + "组件： " + component.getComponent() + "\r\n" + "主机: " + component.getHostname();
						sendMail(subject, content);
					}
				}
			}
			lastComponentStatus = currentComponentStatus;
			return;
		}
		
		private boolean include(List<ComponentStatus> componentStatusList, ComponentStatus selectedComponent) {
			boolean isInclude = false;
			for(ComponentStatus component: componentStatusList) {
				if(component.getId() == selectedComponent.getId() && component.getStatus().equals(selectedComponent.getStatus())) {
					isInclude = true;
					break;
				}	
			}
			return isInclude;
		}
		
		private void sendMail(String subject, String content) {
			String sender = "";
			String userGroupName = "uat-user";
			UserGroupBasic userGroupInfo = alarmBiz.getUserGroupInfoBasicByName(userGroupName);
			List<UserInfo> userInfoList = alarmBiz.getUserInfoByUserGroupId(userGroupInfo.getId());
			String tos = "";
			for(UserInfo user : userInfoList) {
				tos += user.getEmail();
				tos += ",";
			}
			tos = StringUtils.substringBeforeLast(tos, ",");
			alarmSenderService.sendMail(tos, content, subject, sender);
		}
	}
}
